package com.whh.tq;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.whh.tq.bean.Favorite;
import com.whh.tq.bean.QueryResultInfo;
import com.whh.tq.common.AndroidHelper;
import com.whh.tq.common.AsyncLoader;
import com.whh.tq.common.AsyncLoader.Callback;
import com.whh.tq.common.AsyncLoader.Execute;
import com.whh.tq.common.HttpHelper;
import com.whh.tq.common.ReqParamHelper;
import com.whh.tq.common.ResContentHelper;
import com.whh.tq.service.FavoriteService;
import com.whh.tq.service.FavoriteServiceImpl;

public class TrainCodeResultActivity extends Activity {
	private Resources resources; 
	
	private List<QueryResultInfo> queryResultList = new ArrayList<QueryResultInfo>();
	private TimetableResultAdapter adapter;
	private ListView listTrainCodeResult;
	private TextView textTrainCodeResultTitle;
	private TextView textTrainCodeCount;
	private ProgressBar progressLoading;
	private FavoriteService favoriteService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_traincode_result);
		
		init();
		
		//取得intent传递的值
		Bundle bundle = this.getIntent().getExtras();
		final String date = bundle.getString("date");
		String[] strArray=date.split("-");
		final String year = strArray[0];
		final String month = strArray[1];
		final String day = strArray[2];
		final String trainCode = bundle.getString("trainCode");
		
		//初始显示
		textTrainCodeResultTitle.setText(trainCode.toUpperCase());
		textTrainCodeCount.setText(resources.getString(R.string.text_loading));
		
		//异步加载结果
		AsyncLoader.execute(new Execute() {
			@Override
			public Object execute() {
				String res = HttpHelper.getHtml(ReqParamHelper.getTrainCodeGetDataUrl(year, month, day, trainCode),ReqParamHelper.REFERER_TRAINCODE);
				//判断是否有验证码错误等问题
				if(res == null){
					return resources.getString(R.string.text_query_error);
				}else if(res.indexOf(resources.getString(R.string.text_query_error))>0){
					return resources.getString(R.string.text_query_error);
				}
				queryResultList=ResContentHelper.parseTrainCodeResContent(res);
				return null;
			}
		}, new Callback() {
			@Override
			public void callback(Object obj) {	
				if(null != obj){
					AndroidHelper.showToast(TrainCodeResultActivity.this,obj.toString());
				}else {
					if (null == adapter) {
						adapter = new TimetableResultAdapter();
						listTrainCodeResult.setAdapter(adapter);
					} else {
						adapter.notifyDataSetChanged();
					}					
				}
				String text = resources.getString(R.string.text_total_station_count).replace("XX", queryResultList.size()+"");
				if(queryResultList.size()>0){
					text=queryResultList.get(0).getStation()+"->"+queryResultList.get(queryResultList.size()-1).getStation()+" "+text;
				}
				textTrainCodeCount.setText(text);			
				progressLoading.setVisibility(View.GONE);
			}
		});
	}

	/**
	 * 初始化赋值并注册事件
	 */
	private void init() {
		resources = getApplicationContext().getResources();
		progressLoading = (ProgressBar)findViewById(R.id.progress_loading);
		textTrainCodeResultTitle = (TextView)findViewById(R.id.text_trainCode_result_title);
		textTrainCodeCount = (TextView)findViewById(R.id.text_trainCode_count);
		listTrainCodeResult = (ListView)findViewById(R.id.list_trainCode_result);
		favoriteService = new FavoriteServiceImpl(getApplicationContext());
		//将listView的每一项,都看做是菜单项,进行注册
		registerForContextMenu(listTrainCodeResult);
	}

	/**
	 * 长按listview中的item弹出菜单
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		//获取当前长按的下标
	    int i = ((AdapterContextMenuInfo)menuInfo).position; 
		String station = queryResultList.get(i).getStation();
		menu.setHeaderTitle(station);
		menu.add(0, 1, 0, resources.getString(R.string.text_menu_favorite)).setIcon(android.R.drawable.ic_menu_add);
	}
	
	/**
	 * 弹出菜单点击
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		//menuInfo中包含很多属性，其中id就是ListView的Item的id，targetView则是ListView中Item的view
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); 
		// int itemId = Integer.valueOf(menuInfo.id+"");
		// View v = listTrainCodeResult.getChildAt(itemId);
		View v = menuInfo.targetView;
		TextView textStation = (TextView)v.findViewById(R.id.text_station);
		String station = textStation.getText().toString();
		if(!favoriteService.isExits(null, station)){
			Favorite fav = new Favorite();
			fav.setStation(station);
			favoriteService.save(fav);
		}
		AndroidHelper.showToast(getApplicationContext(),resources.getString(R.string.text_menu_favorite)+":"+station);
		return true;
		//return super.onContextItemSelected(item);
	}
	
	/**
	 * 按下手机菜单键，弹出菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 0, "delete").setIcon(android.R.drawable.ic_menu_delete);
		menu.add(0, 2, 0, "add").setIcon(android.R.drawable.ic_menu_add);
		menu.add(0, 3, 0, "edit").setIcon(android.R.drawable.ic_menu_edit);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 弹出菜单点击
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case 1:
				AndroidHelper.showToast(getApplicationContext(), "delete");
			case 2:
				AndroidHelper.showToast(getApplicationContext(), "add");
			case 3:
				AndroidHelper.showToast(getApplicationContext(), "edit");
		}
		return super.onContextItemSelected(item);
	}
	
	
	private class TimetableResultAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return queryResultList.size();
		}

		@Override
		public Object getItem(int position) {
			return queryResultList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_traincode_result, null);
			QueryResultInfo result = queryResultList.get(position);
			TextView textStation = (TextView) view.findViewById(R.id.text_station);
			TextView textFromTime = (TextView) view.findViewById(R.id.text_fromTime);
			TextView textToTime = (TextView) view.findViewById(R.id.text_toTime);
			TextView textUsedTime = (TextView) view.findViewById(R.id.text_usedTime);
			TextView textSeat = (TextView) view.findViewById(R.id.text_price);
			
			textStation.setText(result.getStation());
			textFromTime.setText(result.getFromTime());
			textToTime.setText(result.getToTime());
			textUsedTime.setText(result.getUsedTime());
			textSeat.setText(result.getTimeTableSeatInfo());
			//view.findViewById(R.id.layout_price).setVisibility(View.GONE);
			return view;
		}

	}
}
